'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 黑场
 * @author sundbcn@gmail.com (sun debing)
 */
var _ = require('lodash');
var dataApi = require('../libs/dataApi');
var constantUtil = require('../util/constantUtil.js');

/**
 * 配置
 * @return {[type]}     [description]
 */
exports.getConf = function (shop_id) {
    var conf = dataApi.black_market.findById(shop_id);
    if (!conf) {
        console.error('not find shop_id black market:', shop_id);
        return [];
    }
    return conf;
};

/**
 * 黑市触发概率
 * @return {[type]}     [description]
 */
exports.isTrigger = function (value) {
    var random_num = _.random(0, 100);
    var list = [];
    var id = 0;
    dataApi.black_market_appear.any(function (item) {
        if ((+value) >= item.id) {
            id = item.id;
        }
    });

    if (!id) {
        return false;
    }
    var conf = dataApi.black_market_appear.findById(id);

    if (random_num <= conf.probability) {
        return true;
    } else {
        return false;
    }
};

/**
 * 获取黑场物品
 * @return {[type]}     [description]
 */
exports.getBlackMarketReward = function () {
    var black_market_num = constantUtil.value('black_market_num') || 0;
    var reward_all_list = [];
    var must_appear_list = [];

    var total_probability = 0;
    dataApi.black_market.each(function (item1) {
        var item = _.clone(item1, true);
        if (!!item.must_appear) {
            must_appear_list.push(item);
        } else {
            total_probability += item.probability;
            item.total_probability = total_probability;
            reward_all_list.push(item);
        }
    });
    if (must_appear_list.length > black_market_num) {
        must_appear_list = _.slice(must_appear_list, 0, black_market_num);
    }

    var ii = 0;
    var random_list = [];
    _.forEach(must_appear_list, function (item) {
        random_list.push(item);
    });
    while (random_list.length < black_market_num) {
        ii++;

        var random_item = _randomItem(reward_all_list, total_probability);

        if (_.indexOf(random_list, random_item) == -1) {
            random_list.push(random_item);
        }
        if (ii >= 100000) {
            console.log('fuck you lucky is 0');
            return [];
        }
    }
    return random_list;
};

var _randomItem = function (list, total_probability) {
    var item;
    var random = _.random(0, total_probability - 1);
    _.some(list, function (pro_item) {
        if (pro_item.total_probability >= random) {
            item = pro_item;
            return true;
        }
    });
    return item;
};
